import { OSS_STS } from '@/api/miva';
import { ossSTS } from '@/api/mivawork/resource.js';

const state = {
  stsCache: null,
  stsCache_miva: null
};

const mutations = {
  SAVE_STS: (state, data) => {
    state.stsCache = data;
  },
  SAVE_STS_MIVA: (state, data) => {
    state.stsCache = data;
  }
};

const actions = {
  async  getSTS({ state, commit }) {
    const { stsCache } = state;

    // if (stsCache && Date.now() / 1000 + 30 < stsCache.Expiration) {
    if (stsCache && Date.now() + 3000 < new Date(stsCache.Expiration).getTime()) {
      return console.log('sts密钥正常');
    }

    const { data = null } = await OSS_STS() || {};
    console.log(data.Expiration);
    if (!data) {
      return console.log('sts密钥获取失败');
    }
    commit('SAVE_STS', data);
    console.log(data);
    console.log(`临时密钥保存成功有效期至:${new Date(data.Expiration).toLocaleString()}`);
  },
  async  getSTS_miva({ state, commit }) {
    const { stsCache_miva } = state;
    if (stsCache_miva && Date.now() + 3000 < new Date(stsCache_miva.Expiration).getTime()) {
      return console.log('sts密钥正常');
    }
    const { data = null } = await ossSTS() || {};
    if (!data) {
      return console.log('sts密钥获取失败');
    }
    commit('SAVE_STS_MIVA', data);
    console.log(`临时密钥保存成功有效期至:${new Date(data.Expiration).toLocaleString()}`);
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
